﻿using System;
using System.Web;
using SyCODE.Component;
using SyCODE.Component.DataFactory;
using System.Data.Common;
using System.Collections.Specialized;
using SyCODE.Component.Cryptography;
using SyCODE.Component.Security;
using SyCODE.MailSender;

namespace SyCODE.Blog
{
    /// <summary>
    /// ForgetPassword.aspx 的处理程序
    /// 作用：
    ///   用随机生成新密码或输入的密码替换旧的密码
    /// </summary>
    public class ForgetPassword : IHttpHandler
    {
        public bool IsReusable
        {
            get
            {
                return true;
            }
        }
        public void ProcessRequest(HttpContext context)
        {
            //获取并删除临时授权
            Ticket ticket = Ticket.Get("answer");
            Ticket.Remove("answer");

            if (Ticket.Authenticate(ticket))
            {
                NameValueCollection nvc = new NameValueCollection(context.Request.Form);
                nvc.Set("account", ticket.Name);
                nvc.Set("answer", HttpUtility.HtmlDecode(ticket.UserData));

                string pwd = nvc["pwd"];
                //随机生成密码
                if (nvc["mode"] != "0")
                {
                    pwd = Function.RandomString(8);
                }

                nvc.Set("pwd", SHA1.Encrypt(pwd));

                DBAM dbam = new DBAM();
                dbam.BuildParameters("forgetwpd", nvc);

                try
                {
                    if (dbam.Execute() > 0)
                    {
                        //发送密码修改通知
                        object[] results = dbam.GetResults();

                        Message message = new Message();
                        message.Mail = (string)results[0];
                        message.Name = (string)results[1];
                        message.Subject = StringResource.GetField("forgetpasswordmessagesub");
                        message.Body = pwd;

                        MailSender.Processor.Assign(message);

                        context.Response.Write(pwd);
                    }
                    else
                    {
                        context.Response.Write("0");
                    }
                }
                finally
                {
                    dbam.Dispose();
                }
            }
            else
            {
                Function.ClientScript("previous(2);alert('" + StringResource.GetField("questionfaild") + "');");
            }
        }
    }
}
